#include <QRegularExpression>
#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "global.h"
#include "httpmgr.h"
#include <QJsonObject>
#include "clickedlabel.h"

registerDialog::registerDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::registerDialog)
{
    ui->setupUi(this);
    ui->password_lineEdit->setEchoMode(QLineEdit::Password);
    ui->verify_lineEdit->setEchoMode(QLineEdit::Password);
    ui->user_lineEdit->setPlaceholderText("请输入用户名");
    ui->email_lineEdit->setPlaceholderText("请输入邮箱");
    ui->password_lineEdit->setPlaceholderText("请输入密码");
    ui->verify_lineEdit->setPlaceholderText("请确认密码");
    ui->verify_code_lineEdit->setPlaceholderText("请输入验证码");

    initHttpHandlers();//注册回调函数

    //设备错误提示的状态并刷新，使之显示为绿色
    ui->tip_label->setProperty("state","normal");
    repolish(ui->tip_label);

    ui->tip_label->clear();

    connect(ui->user_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkUserValid();
    });
    connect(ui->email_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkEmailValid();
    });
    connect(ui->password_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkPassValid();
    });
    connect(ui->verify_code_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkVarifyValid();
    });
    connect(ui->verify_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkPassVarifyValid();
    });

    //当http服务结束之后，http模块会发信号让注册模块去接收
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_http_finish,
            this,&registerDialog::slot_reg_mod_finish);

    //设置浮动显示手形状(设置密码的可见和不可见)
    ui->pass_visible->setCursor(Qt::PointingHandCursor);
    ui->confirm_visible->setCursor(Qt::PointingHandCursor);

    ui->pass_visible->SetState("unvisible","unvisible_hover","","visible",
                               "visible_hover","");

    ui->confirm_visible->SetState("unvisible","unvisible_hover","","visible",
                                  "visible_hover","");

    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
        auto state = ui->pass_visible->GetCurState();
        if(state == ClickLbState::Normal){
            ui->password_lineEdit->setEchoMode(QLineEdit::Password);
        }else{
            ui->password_lineEdit->setEchoMode(QLineEdit::Normal);
        }
    });
    connect(ui->confirm_visible,&ClickedLabel::clicked,this,[this](){
        auto state = ui->confirm_visible->GetCurState();
        if(state == ClickLbState::Normal){
            ui->verify_lineEdit->setEchoMode(QLineEdit::Password);
        }else{
            ui->verify_lineEdit->setEchoMode(QLineEdit::Normal);
        }
    });

    //点击界面的取消按钮时发送信号提醒主界面返回登录界面
    connect(ui->cancel_btn,&QPushButton::clicked,this,&registerDialog::sinals_switch_to_login);
}

registerDialog::~registerDialog()
{
    qDebug()<<"~registerDialog()";
    delete ui;
}

void registerDialog::on_get_code_btn_clicked()
{
    auto email = ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|\_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if(match){
        //发送hhtp请求验证码
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_varifycode"),
                                            json_obj,ReqId::ID_GET_VARIFY_CODE,Modules::REGISTERMOD);
    }else{
        showTip("邮箱格式错误",false);
    }
}

void registerDialog::slot_reg_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS){
        showTip("网络请求错误",false);
        return;
    }
    //解析json字符串，转化成QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(jsonDoc.isNull()){
        showTip("json解析失败",false);
        return;
    }
    if(!jsonDoc.isObject()){
        showTip("json解析失败",false);
        return;
    }
    //根据id执行对应的回调函数
    _handlers[id](jsonDoc.object());
}

void registerDialog::showTip(const QString& str,bool ok)
{
    ui->tip_label->setText(str);
    if(ok){
        ui->tip_label->setProperty("state","normal");
    }
    else{
        ui->tip_label->setProperty("state","error");
    }
    repolish(ui->tip_label);
}

void registerDialog::initHttpHandlers()
{
    //注册验证码回包的逻辑
    _handlers.insert(ReqId::ID_GET_VARIFY_CODE,[this](const QJsonObject& jsonObject){
       int error = jsonObject["error"].toInt();
       if(error != ErrorCodes::SUCCESS){
           showTip("参数错误",false);
           qDebug()<<"registerDialog::initHttpHandlers():参数错误";
           return;
       }
       QString email = jsonObject["email"].toString();
       qDebug()<<"email is "<<email;
       showTip("验证码已经发送，请注意查收",true);
    });

    //注册 注册用户的逻辑
    _handlers.insert(ReqId::ID_REG_USER,[this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(error != ErrorCodes::SUCCESS){
            showTip("参数错误",false);
            return;
        }
        auto email = jsonObj["email"].toString();
        showTip("用户注册成功,再次点击确定按钮返回登录界面",true);
        qDebug()<<"user uid is "<<jsonObj["uid"].toString();
        qDebug()<<"email is "<<email;
    });
}

void registerDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips,false);
}

void registerDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->tip_label->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

bool registerDialog::checkUserValid()
{
    if(ui->user_lineEdit->text()==""){
        AddTipErr(TipErr::TIP_USER_ERR,"用户名不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool registerDialog::checkPassValid()
{
    QString pass = ui->password_lineEdit->text();
    if(pass.length()<6 || pass.length()>15){
        //密码长度不符合要求
        AddTipErr(TipErr::TIP_PWD_ERR,"密码长度应该为6-15位");
        return false;
    }
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_PWD_ERR,"不能包含非法字符");
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    return true;
}

bool registerDialog::checkEmailValid()
{
    QString email = ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|\_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,"邮箱地址不正确");
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool registerDialog::checkVarifyValid()
{
    QString pass = ui->verify_code_lineEdit->text();
    if(pass.isEmpty()){
        AddTipErr(TipErr::TIP_VARIFY_ERR,"验证码不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}

bool registerDialog::checkPassVarifyValid()//检查重新输入一遍的密码是否是正确的
{
    QString confrim = ui->verify_lineEdit->text();
    if(confrim.isEmpty()){
        AddTipErr(TipErr::TIP_CONFIRM_ERR,"请重新输入一遍密码");
        return false;
    }
    if(confrim != ui->password_lineEdit->text()){
        AddTipErr(TipErr::TIP_CONFIRM_ERR,"确认密码和原密码不相同");
        return false;
    }
    DelTipErr(TipErr::TIP_CONFIRM_ERR);
    return true;
}


void registerDialog::on_sure_btn_clicked()
{
    if(ui->tip_label->text()=="用户注册成功,再次点击确定按钮返回登录界面"){
        emit sinals_switch_to_login();
        return;
    }
    if(!checkUserValid()||!checkPassValid()||!checkEmailValid()||!checkVarifyValid()||!checkPassVarifyValid()){
        return;
    }
    qDebug()<<"注册用户逻辑";
    QJsonObject json_obj;
    json_obj["user"] = ui->user_lineEdit->text();
    json_obj["email"] = ui->email_lineEdit->text();
    json_obj["passwd"] = xorString(ui->password_lineEdit->text());
    json_obj["confirm"] = xorString(ui->verify_lineEdit->text());
    qDebug()<<json_obj["passwd"];
    json_obj["varifycode"] = ui->verify_code_lineEdit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_register"),
                                        json_obj,ReqId::ID_REG_USER,Modules::REGISTERMOD);

}


